-module(mochiweb_hello).
-export([start/0, loop/1, stop/0, handle_req/1]).
-define(DEFAULTS, [{name, ?MODULE},
                   {port, 8084}]).

-include("../../include/ewgi.hrl").

start() ->
    mochiweb_http:start([{loop, fun ?MODULE:loop/1} | ?DEFAULTS]).

stop() ->
    mochiweb_http:stop(?MODULE).

loop(Req) ->
    error_logger:error_report(Req),
    M = ewgi_mochiweb:new(fun ?MODULE:handle_req/1),
    error_logger:error_report(Req),
    M:run(Req).

handle_req(Ctx) ->
    error_logger:info_report(Ctx),
    {ok, C} = sgte:compile("
<html>
<head><title>Hello world</title></head>
<body>
<h1>Hello world !!!!</h1>
<form name='frmPost' method='POST' action='hello'>
<label>aaa</label><input type='text' name='aaa' value='bbb'><br>
<input type='submit' name='send' value='doPost'>
</form>
</body>
</html>"),
    Body = sgte:render(C, []),
    ewgi_api:set_response(#ewgi_response{status={200, "OK"}, message_body=Body, headers=[]}, Ctx).
